//
//  WCTFriendService.m
//  WeChatTool
//
//  Created by TerryChe on 2016/12/6.
//  Copyright © 2016年 TerryChe. All rights reserved.
//

#import "WCTMMService.h"
#import "WCTFriend.h"
#import "WCTChatMsg.h"
#import "WCTConfig.h"

@interface WCTMMService()

@property (nonatomic, strong) NSString* path;
@property (nonatomic, strong) WCTFriend* me;
@property (nonatomic, strong) NSMutableDictionary* friendMD5Dic;
@property (nonatomic, strong) NSString* filePath;

@property (nonatomic, strong) NSMutableArray* cacheMoney;

@property (nonatomic, assign) bool isChatroom;

@end

@implementation WCTMMService

-(instancetype)initWith:(NSString *)path AndME:(WCTFriend *)me AndFilePath:(NSString *)filePath{
    if(self == [super init])
    {
        self.path = path;
        self.me = me;
        self.filePath = filePath;
        
        self.cacheMoney = [NSMutableArray arrayWithCapacity:[WCTConfig sharedInstance].batchCount];
        self.friendMD5Dic = [NSMutableDictionary dictionaryWithCapacity:[WCTConfig sharedInstance].batchCount];
        
        for (NSDictionary *tempDic in [WCTConfig.sharedInstance.cacheFriend allValues]) {
            WCTFriend *friend = [WCTFriend WCTFriendByDic:tempDic];
            
            if (friend == nil) {
                continue;
            }
            
            if (![friend.wenober isEqualToString:@""]) {
                [self.friendMD5Dic setObject:friend.wenober forKey:[[WCTConfig sharedInstance] md5:friend.wenober]];
                
                if (![friend.uwenober isEqualToString:@""]) {
                    [self.friendMD5Dic setObject:friend.wenober forKey:[[WCTConfig sharedInstance] md5:friend.uwenober]];
                }
                
                if (![friend.name isEqualToString:@""]) {
                    [self.friendMD5Dic setObject:friend.wenober forKey:[[WCTConfig sharedInstance] md5:friend.name]];
                }
            }
        }
        
        //初始化cacheChatMsg
        NSString *chatroomPlistPath = [self.filePath stringByAppendingPathComponent:str_wct_chatmsg];
        if ([[NSFileManager defaultManager] fileExistsAtPath:chatroomPlistPath]) {
            if (WCTConfig.sharedInstance.cacheChatMsg.count == 0) {
                NSDictionary *tempDic = [NSDictionary dictionaryWithContentsOfFile:chatroomPlistPath];
                if (tempDic != nil) {
                    [WCTConfig.sharedInstance.cacheChatMsg setDictionary:tempDic];
                }
            }
        }
        else {
            [WCTConfig.sharedInstance.cacheChatMsg removeAllObjects];
        }
        
        //初始化cacheImg
        NSString *imgPlistPath = [self.filePath stringByAppendingPathComponent:str_wct_img];
        if ([[NSFileManager defaultManager] fileExistsAtPath:imgPlistPath]) {
            if (WCTConfig.sharedInstance.cacheImg.count == 0) {
                NSArray *tempArray = [NSArray arrayWithContentsOfFile:imgPlistPath];
                if (tempArray != nil) {
                    [WCTConfig.sharedInstance.cacheImg setArray:tempArray];
                }
            }
        }
        else {
            [WCTConfig.sharedInstance.cacheImg removeAllObjects];
        }
    }
    
    return self;
}

-(void)handleChatData{
    NSString* dbPath = [self.path stringByAppendingPathComponent:str_db_mm];
    if (![[NSFileManager defaultManager] fileExistsAtPath:dbPath]) {
        log(@"数据库不存在：%@", dbPath);
        return;
    }
    
    FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
    [db open];
    NSArray *source = [db syncExecuteQuery:@"select name from sqlite_master where type='table' and name like 'Chat_%' order by name"];
    [db close];
    
    for (NSDictionary *dic in source) {
        NSString* tableName = dic[@"name"];
        
        if (tableName != nil && [tableName hasPrefix:@"Chat_"]) {
            NSString* friendCode = [tableName stringByReplacingOccurrencesOfString:@"Chat_" withString:@""];
            NSString* friendID = [self.friendMD5Dic objectForKey:friendCode];
            
            if (friendID == nil || [friendID isEqualToString:@""]) {
                continue;
            }
            
            _isChatroom = [friendID hasSuffix:@"@chatroom"];
            
            if (_isChatroom) {//暂时忽略群聊
                continue;
            }
            
            UInt64 flagTime = [WCTConfig sharedInstance].beginDate;
            id tempValue = [WCTConfig.sharedInstance.cacheChatMsg objectForKey:tableName];
            if (tempValue != nil) {
                UInt64 cacheTime = [tempValue unsignedLongLongValue];
                
                if (cacheTime > flagTime) {
                    flagTime = cacheTime;
                }
            }
            
            @try {
                FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
                [db open];
                NSArray *table = [db syncExecuteQuery:[NSString stringWithFormat:@"select * from %@  where CreateTime > %llu ORDER BY CreateTime", tableName, flagTime]];
                [db close];
                [self handleChatTableData:table AndFriendID:friendID AndTableName:tableName];
            }
            @catch (NSException *exception) {
                log(@"捕捉到错误 %@ ：%@", exception.name ,exception.reason);
            }
        }
    }
}

-(void)handleChatTableData:(NSArray *)tableData AndFriendID:(NSString *)friendID AndTableName:(NSString *)tableName{
    if (tableData.count == 0) {
        return;
    }
    
    [_cacheMoney removeAllObjects];
    NSMutableArray *chatMsgArr = [NSMutableArray arrayWithCapacity:[WCTConfig sharedInstance].batchCount];
    
    log(@"%@ 聊天记录 总数：%lu", friendID, (unsigned long)tableData.count);
    
    for (NSDictionary* row in tableData) {
        NSString* friendCode = [tableName stringByReplacingOccurrencesOfString:@"Chat_" withString:@""];
        int mesLocalID = [row[@"MesLocalID"] intValue];
        int type = [row[@"Type"] intValue];
        bool isSend = ![row[@"Des"] boolValue];
        
        NSString *content = row[@"Message"];
        NSString *user = @"";
        
        if (content == nil || [content  isEqual: @""]) {
            log(@"聊天信息解析错误：%@", row)
            continue;
        }
        
        if (_isChatroom) {
            NSRange rang = [row[@"Message"] rangeOfString:@":\n"];
            if (rang.length > 0) {
                user = [row[@"Message"] substringToIndex:rang.location];
                content = [row[@"Message"] substringFromIndex:rang.location + rang.length];
            }
        }
        
        if (content == nil || [content  isEqual: @""]) {
            log(@"聊天信息解析错误：%@", row)
            continue;
        }
        
        NSString* svrid = [NSString stringWithFormat:@"%@", row[@"MesSvrID"]];
        if (svrid == nil || [svrid isEqualToString:@"0"] || [svrid isEqualToString:@""]) {
            svrid = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
        }
        
        switch (type) {
            case 1://文字
                break;
            case 10000://系统提示
            {
                NSString *hongbaoIcon = @"<img src=\"SystemMessages_HongbaoIcon.png\"/>";
                if ([content hasPrefix:hongbaoIcon]) {
                    if (isSend == false) {//对方领取我的红包不用记录
                        svrid = @"";
                        NSString *url = [self getValueForXML:content WithKey:@"href"];
                        for (NSString* pay in WCTConfig.sharedInstance.cachePayMsgid) {
                            if ([url containsString:pay]) {
                                svrid = pay;
                                break;
                            }
                        }
                        
                        [WCTConfig.sharedInstance.cachePayMsgid removeObject: svrid];
                        
                        WCTChatMsg *msg = [WCTChatMsg WCTChatMsgByTalter:friendID Content:@"0" Issend:isSend Resvred: @"" WechatID:[self.me getWeChatNo] Sate: 3 Time:row[@"CreateTime"] SermsgID:svrid];
                        [_cacheMoney addObject:msg];
                    }
                    
                    isSend = true;
                    NSString *temp = [content stringByReplacingOccurrencesOfString:hongbaoIcon withString:@""];
                    
                    NSRange end = [temp rangeOfString:@"<_wc_custom_link_"];
                    content = [[[temp substringToIndex:end.location] stringByReplacingOccurrencesOfString:@" " withString:@""] stringByAppendingString:@"红包"];
                }
            }
                break;
            case 3://图片
                //                <?xml version="1.0"?>
                //                <msg>
                //                <img aeskey="203c0281a85c48e8b0a2a876690e46bb" encryver="0" cdnthumbaeskey="203c0281a85c48e8b0a2a876690e46bb" cdnthumburl="304e020100044730450201000204031a322502033d14bb02044e0e337902045a263bc00420777869645f363770776d35666566773533323232305f313531323435353130330204010800020201000400" cdnthumblength="4398" cdnthumbheight="120" cdnthumbwidth="120" cdnmidheight="0" cdnmidwidth="0" cdnhdheight="0" cdnhdwidth="0" cdnmidimgurl="304e020100044730450201000204031a322502033d14bb02044e0e337902045a263bc00420777869645f363770776d35666566773533323232305f313531323435353130330204010800020201000400" length="34002" md5="34fbfb7423b7899f2239271db910836b" />
                //                </msg>
            {
                NSString *lastPath = [NSString stringWithFormat: @"Img/%@/%d.pic", friendCode, mesLocalID];
                NSString *imgPath = [self.path stringByAppendingPathComponent: lastPath];
                NSString *imgThumPath = [imgPath stringByAppendingString:@"_thum"];
                
                //文件名
                NSString *fileName = @"";
                
                //上传缩略图
                if ([[NSFileManager defaultManager] fileExistsAtPath:imgThumPath]) {
//                    [self uploadFileName:fileName withPath:imgThumPath Type:1];
                    fileName = [self uploadFileWithPath:imgThumPath Type:1];
                }
                
                //上次大图
                if ([[NSFileManager defaultManager] fileExistsAtPath:imgPath]) {
                    if ([fileName isEqualToString:@""]) {
                        fileName = [self uploadFileWithPath:imgPath Type:1];
                    }
                    else {
                        NSString *hdFileName = [fileName stringByAppendingString:@"_hd"];
                        [self uploadFileName:hdFileName withPath:imgPath Type:1];
                    }
                }
                
                if (![fileName isEqualToString:@""]) {
                    content = [NSString stringWithFormat: @"imgs[%@]", fileName];
                }
            }
                break;
            case 34://语音
                //                <msg><voicemsg endflag="1" cancelflag="0" forwardflag="0" voiceformat="4" voicelength="2840" length="4971" bufid="362697283806888330" clientmsgid="49fc06cef28dd6d577fcb974bc442d41wxid_67pwm5fefw532221_1512455111" fromusername="jackche2010" /></msg>
            {
                NSString *lastPath = [NSString stringWithFormat: @"Audio/%@/%d.aud", friendCode, mesLocalID];
                NSString *audioPath = [self.path stringByAppendingPathComponent: lastPath];
                
                if (![[NSFileManager defaultManager] fileExistsAtPath:audioPath]) {
//                    log(@"语音文件不存在：%@", audioPath)
                    continue;
                }
                
                NSString *fileName = [self uploadFileWithPath:audioPath Type:0];
                content = [NSString stringWithFormat: @"audio[%@]", fileName];
            }
                break;
            case 47://自定义表情图片
                ///Library/WechatPrivate/emoticonPIC/846f30447c5c4c9beefeb5a61bec0ba3.pic
                //                <msg><emoji md5="846f30447c5c4c9beefeb5a61bec0ba3" type="2" len = "19922" productid="com.tencent.xin.emoticon.tusiji" width="200" height="200"></emoji><gameext type="0" content="0" ></gameext></msg>

                //Library/WechatPrivate/emoticonAutoClean/846f30447c5c4c9beefeb5a61bec0ba3.pic
                //                <msg><emoji fromusername = "jackche2010" tousername = "wxid_67pwm5fefw5322" type="2" idbuffer="media:0_0" md5="52972cbf0284d0a99ce299d439c98c8b" len = "8636" productid="com.tencent.xin.emoticon.person.stiker_149788330120156a43d7278113" androidmd5="52972cbf0284d0a99ce299d439c98c8b" androidlen="8636" s60v3md5 = "52972cbf0284d0a99ce299d439c98c8b" s60v3len="8636" s60v5md5 = "52972cbf0284d0a99ce299d439c98c8b" s60v5len="8636" cdnurl = "http://emoji.qpic.cn/wx_emoji/Jx9FibicwTRPSpicGTLLVMRhMyibP1qMdPMcaCchfaHj4bKFkZ3ts9CEecODI4Jad6SW/" designerid = "" thumburl = "http://mmbiz.qpic.cn/mmemoticon/Q3auHgzwzM6n8rbxOAOExJ1NSiaFXNJZHZOKQN6agljyUyDQp0Q2A2fk72riabHEN5/0" encrypturl = "http://emoji.qpic.cn/wx_emoji/Jx9FibicwTRPSpicGTLLVMRhMyibP1qMdPMcaCchfaHj4bJZAC86Cw8qwvVuibBWQ8T6M/" aeskey= "6320e0411e080340f668576976cdc4f4" externurl = "" externmd5 = "" width= "240" height= "240" ></emoji> <gameext type="0" content="0" ></gameext></msg>
            {
                NSString *libraryPath = [[self.path stringByDeletingLastPathComponent] stringByDeletingLastPathComponent];
                NSString *md5 = [self getValueForXML:content WithKey:@"md5"];
                
                //emoticonAutoClean
                NSString *imgPath = [libraryPath stringByAppendingPathComponent:str_library_emoticonAutoClean];
                imgPath = [imgPath stringByAppendingPathComponent: [md5 stringByAppendingString:@".pic"]];
                if ([[NSFileManager defaultManager] fileExistsAtPath:imgPath]) {
                    NSString *fileName = [self uploadFileWithPath:imgPath Type:1];
                    content = [NSString stringWithFormat: @"img[%@]", fileName];
                    break;
                }
                
                imgPath = [libraryPath stringByAppendingPathComponent:str_library_emoticonPIC];
                imgPath = [imgPath stringByAppendingPathComponent: [md5 stringByAppendingString:@".pic"]];
                if ([[NSFileManager defaultManager] fileExistsAtPath:imgPath]) {
                    NSString *fileName = [self uploadFileWithPath:imgPath Type:1];
                    content = [NSString stringWithFormat: @"img[%@]", fileName];
                    break;
                }
                
                NSString *imgUrl = [self getValueForXML:content WithKey:@"cdnurl"];
                if (![imgUrl  isEqual: @""]) {
                    //下载图片
                    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
                    NSString *imgKey = [[WCTConfig sharedInstance] sha1WithData:data];
                    content = [NSString stringWithFormat: @"img[%@]", imgKey];
                    [self uploadFileName:imgKey withData:data Type:1];
                }
            }
                break;
            case 50://视频聊天 或者 语音聊天
                //                <voipinvitemsg><roomid>257767277</roomid><key>6494852845231775370</key><status>2</status><invitetype>0</invitetype></voipinvitemsg><voipextinfo><recvtime>1512455257</recvtime></voipextinfo>
                content = @"<发起语音聊天>";
                type = 1;
                break;
            case 42://名片
                //                bean.ad_chatting_content = "MP[" + bean.ad_chatting_content.substring(bean.ad_chatting_content.indexOf("nickname=\"") + 10).split("\"")[0] + "]";
                //                <?xml version="1.0"?>
                //                <msg bigheadimgurl="http://wx.qlogo.cn/mmhead/ver_1/xPZv9zHwnfTRCRfGia1EvNVbMtJIf0qjZ52fOq6DjrviaialmiafEjPY08F1LfB1ftexfo43QnnONR55zWczoia5adgSbiafmnbNI6uTfRgpibd4Fs/0" smallheadimgurl="http://wx.qlogo.cn/mmhead/ver_1/xPZv9zHwnfTRCRfGia1EvNVbMtJIf0qjZ52fOq6DjrviaialmiafEjPY08F1LfB1ftexfo43QnnONR55zWczoia5adgSbiafmnbNI6uTfRgpibd4Fs/132" username="v1_0325ed6eaa48b3e104b9f1714eee7a675c04d519813188ca49d4b03826ccff95fdc2c2189efce30d6ac78c7e4401ee16@stranger" nickname="阿良Y3呼叫中心系统" fullpy="aliangY3hujiaozhongxinjitong" shortpy="" alias="" imagestatus="3" scene="17" province="广东" city="中国" sign="" sex="1" certflag="0" certinfo="" brandIconUrl="" brandHomeUrl="" brandSubscriptConfigUrl="" brandFlags="0" regionCode="CN_Guangdong_Guangzhou" antispamticket="v2_9204b24f0e695a9a9d5569cb619cc099be7bd9b727eca2dec4a5d6d6bfe41874a776cacabaaf890bdaae6af3596aeaa8@stranger" />
                content = [NSString stringWithFormat: @"MP[%@]", [self getValueForXML:content WithKey:@"nickname"]];
                break;
            case 43://小视频
                //                bean.ad_chatting_content = "<暂不支持显示视频>";
                //                <?xml version="1.0"?>
                //                <msg>
                //                <videomsg aeskey="d5fac3a6774a47c7af47f481051d0599" cdnthumbaeskey="d5fac3a6774a47c7af47f481051d0599" cdnvideourl="304e020100044730450201000204031a322502032f59190204a3a6697102045a263c170420777869645f363770776d35666566773533323232355f313531323435353138390204010800040201000400" cdnthumburl="304e020100044730450201000204031a322502032f59190204a3a6697102045a263c170420777869645f363770776d35666566773533323232355f313531323435353138390204010800040201000400" length="595287" playlength="3" cdnthumblength="4852" cdnthumbwidth="224" cdnthumbheight="400" fromusername="jackche2010" md5="b8a09de14a10fcd259cd430b4cca3a1a" newmd5="082f982c658806670116e4c0bfc8b2b4" isad="0" />
                //                </msg>
                content = @"<暂不支持显示视频>";
                type = 1;
                break;
            case 48://定位
                //                bean.ad_chatting_content = "<暂不支持显示位置>";
                //                <?xml version="1.0"?>
                //                <msg>
                //                <location x="23.134372" y="113.419890" scale="15" label="广州市天河区东澳创业小镇北(奥体南路北)" maptype="roadmap" poiname="天河区东澳创业小镇北(奥体南路北)" />
                //                </msg>
//                content = @"<暂不支持显示位置>";
//                type = 1;
                //a(url)[title]
            {
                NSString *lat = [self getValueForXML:content WithKey:@"x"];
                NSString *lng = [self getValueForXML:content WithKey:@"y"];
                NSString *title = [self getValueForXML:content WithKey:@"label"];
                content = [NSString stringWithFormat:@"a(http://apis.map.qq.com/uri/v1/geocoder?coord=%@,%@&referer=Y3)[%@]", lat, lng, title];
                type = 49;
            }
                break;
            case 49://分享链接
                //我发起了位置共享
                //                <msg><appmsg appid="" sdkver="0"><type>17</type><title><![CDATA[我发起了位置共享]]></title></appmsg><fromusername>jackche2010</fromusername></msg>
                
                //链接
                //                <?xml version="1.0"?>
                //                <msg>
                //                <appmsg appid="" sdkver="0">
                //                <title>迪士尼全攻略！怎样一天刷完上海迪士尼所有热门项目？</title>
                //                <des>最全迪士尼攻略</des>
                //                <action />
                //                <type>5</type>
                //                <showtype>0</showtype>
                //                <soundtype>0</soundtype>
                //                <mediatagname />
                //                <messageext />
                //                <messageaction />
                //                <content />
                //                <contentattr>0</contentattr>
                //                <url>http://mp.weixin.qq.com/s?__biz=MjM5MjAyNzg4MA==&amp;mid=2652628099&amp;idx=1&amp;sn=e498aa127738ce918758da6c189d1fa7&amp;chksm=bd43c1048a344812965fde42e89a0b55d0bec344907cb4549eee023a9737c5fb094c7f9b73d7&amp;mpshare=1&amp;scene=24&amp;srcid=0910OH2DTTbDupAP6uRhAXh5#rd</url>
                //                <lowurl />
                //                <dataurl />
                //                <lowdataurl />
                //                <appattach>
                //                <totallen>0</totallen>
                //                <attachid />
                //                <emoticonmd5 />
                //                <fileext />
                //                <cdnthumbaeskey />
                //                <aeskey />
                //                </appattach>
                //                <extinfo />
                //                <sourceusername>gh_e36ba6bab8b0</sourceusername>
                //                <sourcedisplayname />
                //                <thumburl>http://mmbiz.qpic.cn/mmbiz_jpg/0QyBUDouDuH2ibr7SqXr4sfxhwxN7Kwc7dib3CyDMK4SydWsucAUCibqMGCqibDq4QhdEJExHFdeWSHXSljnWE5Qlw/640?wxtype=jpeg&amp;wxfrom=0</thumburl>
                //                <md5 />
                //                <statextstr />
                //                </appmsg>
                //                <fromusername>jackche2010</fromusername>
                //                <scene>0</scene>
                //                <appinfo>
                //                <version>1</version>
                //                <appname></appname>
                //                </appinfo>
                //                <commenturl></commenturl>
                //                </msg>
                if ([content rangeOfString:@"<type>2001</type>"].location != NSNotFound || [content rangeOfString:@"<type><![CDATA[2001]]></type>"].location != NSNotFound) {//红包
                    
                    svrid = [self getCDATAForXML:content WithKey:@"paymsgid"];
                    [WCTConfig.sharedInstance.cachePayMsgid addObject:svrid];
                    
                    content = @"<你发送了一个微信红包>";
                    type = 1;
                    
                    WCTChatMsg *msg = [WCTChatMsg WCTChatMsgByTalter:friendID Content:@"0" Issend:isSend Resvred: @"" WechatID:[self.me getWeChatNo] Sate: 2 Time:row[@"CreateTime"] SermsgID:svrid];
                    [_cacheMoney addObject:msg];
                } else if ([content rangeOfString:@"<type>2000</type>"].location != NSNotFound || [content rangeOfString:@"<type><![CDATA[2000]]></type>"].location != NSNotFound) {//转帐
                    
                    NSString* money = [self getCDATAForXML:content WithKey:@"feedesc"];
                    
                    int sate = 1;
                    //3是即时收账，5是延时收账
                    if ([content rangeOfString:@"<paysubtype>3</paysubtype>"].location != NSNotFound || [content rangeOfString:@"<paysubtype><![CDATA[3]]></paysubtype>"].location != NSNotFound || [content rangeOfString:@"<paysubtype>5</paysubtype>"].location != NSNotFound || [content rangeOfString:@"<paysubtype><![CDATA[5]]></paysubtype>"].location != NSNotFound) {//领取
                        svrid = [self getCDATAForXML:content WithKey:@"transcationid"];
                        [WCTConfig.sharedInstance.cachePayMsgid removeObject: svrid];
                        
                        content = [NSString stringWithFormat:@"<你已确认收款：%@>", money];
                        sate = 1;
                    }
                    else {//发出
                        svrid = [self getCDATAForXML:content WithKey:@"transcationid"];
                        [WCTConfig.sharedInstance.cachePayMsgid addObject:svrid];
                        
                        content = [NSString stringWithFormat:@"<你发起了一笔转账：%@>", money];
                        sate = 0;
                    }
                    type = 1;
                    money = [money stringByReplacingOccurrencesOfString:@"¥" withString:@""];
                    money = [money stringByReplacingOccurrencesOfString:@"￥" withString:@""];
                    if (sate == 1 && isSend == false) {
                        //对方领取我的转账不用记录
                    }
                    else {
                        WCTChatMsg *msg = [WCTChatMsg WCTChatMsgByTalter:friendID Content:money Issend:isSend Resvred: @"" WechatID:[self.me getWeChatNo] Sate: sate Time:row[@"CreateTime"] SermsgID:svrid];
                        [_cacheMoney addObject:msg];
                    }
                } else if ([content rangeOfString:@"<type>17</type>"].location != NSNotFound) {//位置
                    content = @"<发起了位置共享>";
                    type = 1;
                    
                } else if ([content rangeOfString:@"<type>6</type>"].location != NSNotFound) {//文件
                    content = @"<文件>";
                    type = 1;
                }
                else if ([content rangeOfString:@"<type>5</type>"].location != NSNotFound) {//连接
                    NSRange urlStart = [content rangeOfString:@"<url>"];
                    NSRange urlEnd = [content rangeOfString:@"</url>"];
                    NSRange titleStart = [content rangeOfString:@"<title>"];
                    NSRange titleEnd = [content rangeOfString:@"</title>"];
                    if (urlStart.length > 0 && urlEnd.length > 0 && urlEnd.location > urlStart.location
                        && titleStart.length > 0 && titleEnd.length > 0 && titleEnd.location > titleStart.location) {
                        NSString *url = [content substringWithRange: NSMakeRange(urlStart.location + urlStart.length, urlEnd.location - (urlStart.location + urlStart.length))];
                        NSString *title = [content substringWithRange: NSMakeRange(titleStart.location + titleStart.length, titleEnd.location - (titleStart.location + titleStart.length))];
                        content = [NSString stringWithFormat: @"a(%@)[%@]", url, title];
                    }
                }
                break;
            default:
                content = @"当前版本暂不支持查看此消息，请在手机上查看。";
                type = 10000;
                break;
        }
        
        if (![user isEqualToString:@""]) {
            content = [NSString stringWithFormat:@"%@:%@", user, content];
        }
        
        WCTChatMsg *msg = [WCTChatMsg WCTChatMsgByTalter:friendID Content:content Issend:isSend Resvred: @"" WechatID:[self.me getWeChatNo] Sate: type Time:row[@"CreateTime"] SermsgID:svrid];
        
        [chatMsgArr addObject:msg];
        
        //如果够数，就上传一次聊天记录
        if (chatMsgArr.count == [WCTConfig sharedInstance].batchCount) {
            [self matchCountUploadMsg:chatMsgArr TableName:tableName FriendID:friendID];
            [chatMsgArr removeAllObjects];
        }
    }
    
    if (chatMsgArr.count > 0) {
        [self matchCountUploadMsg:chatMsgArr TableName:tableName FriendID:friendID];
        [chatMsgArr removeAllObjects];
    }
}

-(void)matchCountUploadMsg:(NSArray *)array TableName:(NSString *)tableName FriendID:(NSString *)friendID{
    log(@"%@ 聊天记录 需要上传总数：%lu", friendID, (unsigned long)array.count);
    [self uploadChatMsgBy:array TableName:tableName];
    
    if (_cacheMoney.count > 0) {
        log(@"%@ 红包/转账 需要上传总数：%lu",  friendID, (unsigned long)_cacheMoney.count);
        NSMutableArray *chatMsgList = [NSMutableArray arrayWithCapacity:[WCTConfig sharedInstance].batchCount];
        for (WCTChatMsg* msg in _cacheMoney) {
            NSDictionary *temp = [msg convertToDic:true];
            [chatMsgList addObject:temp];
        }
        
        NSMutableDictionary *dicParams = [NSMutableDictionary dictionaryWithCapacity:[WCTConfig sharedInstance].batchCount];
        [dicParams setObject:chatMsgList forKey:@"list"];
        
        NSString* url = [NSString stringWithFormat:@"%@/api/weichart/PostMoney?format=json&access_token=%@", [WCTConfig sharedInstance].address, [WCTConfig sharedInstance].token];
        OPHRequest* request = [OPHRequest jsonReqeust:url type:OPH_HTTP_POST params:dicParams];
        OPHResponse* response = [[OPHNetwork sharedInstance] syncRequest:request];
        if ([response isRequestOk]) {
            log(@"转账/红包上传成功！");
        }
    }
}

-(void)uploadChatMsgBy:(NSArray *)array TableName:(NSString *)tableName{
    if (array == nil || array.count == 0) {
        return;
    }
    
    NSInteger lastTime = [((WCTChatMsg *)[array lastObject]).time integerValue];
    
    NSMutableArray *chatMsgList = [NSMutableArray arrayWithCapacity:[WCTConfig sharedInstance].batchCount];
    for (WCTChatMsg* msg in array) {
        NSDictionary *temp = [msg convertToDic:false];
        if (temp == nil) {
            continue;
        }
        [chatMsgList addObject:temp];
    }
    
    if (chatMsgList.count == 0) {
        return;
    }
    
    NSMutableDictionary *dicParams = [NSMutableDictionary dictionaryWithCapacity:[WCTConfig sharedInstance].batchCount];
    [dicParams setObject:chatMsgList forKey:@"list"];
    
    NSString* url = [NSString stringWithFormat:@"%@/api/weichart/PostMess?format=json&access_token=%@", [WCTConfig sharedInstance].address, [WCTConfig sharedInstance].token];
    OPHRequest* request = [OPHRequest jsonReqeust:url type:OPH_HTTP_POST params:dicParams];
    OPHResponse* response = [[OPHNetwork sharedInstance] syncRequest:request];
    
    if ([response isRequestOk]) {
        OPHJsonStatusResult* jsonResult = [response expectedJsonStatusResultObject];
        
        log(@"聊天记录上传 lastTime:%ld %@", (long)lastTime, [jsonResult description]);
        
        if ([jsonResult isResultSuccess]) {
            //Key相同覆盖原本的Value
            [self cacheChatMsg:tableName AndLastTime:lastTime];
        }
        else{
            [[OPHNetwork sharedInstance] throwNetworkException:[NSString stringWithFormat:@"聊天记录上传 %@", [jsonResult description]]];
        }
    }
}

-(void)cacheChatMsg:(NSString *)tableName AndLastTime:(NSInteger)lastTime{
    //Key相同覆盖原本的Value
    [WCTConfig.sharedInstance.cacheChatMsg setObject:@(lastTime) forKey:tableName];
    
    //写入plist
    NSString *filePath = [self.filePath stringByAppendingPathComponent:str_wct_chatmsg];
    BOOL succeed = [WCTConfig.sharedInstance.cacheChatMsg writeToFile:filePath atomically:YES];
    log(@"cacheChatMsg: %d====Count：%d", succeed, (int)WCTConfig.sharedInstance.cacheChatMsg.count);
}

-(NSString *)uploadFileWithPath:(NSString *)path Type:(int)type {
    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
    NSString *str = [[WCTConfig sharedInstance] sha1WithData:data];
    
    [self uploadFileName:str withData:data Type:type];
    
    return str;
}

- (void)uploadFileName:(NSString *)fileName withPath:(NSString *)path Type:(int)type {
    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
    
    [self uploadFileName:fileName withData:data Type:type];
}

- (void)uploadFileName:(NSString *)fileName withData:(NSData *)data Type:(int)type{
    if ([WCTConfig.sharedInstance.cacheImg containsObject:fileName]){
        NSLog(@"本地记录已上传：%@", fileName);
        return;
    }
    
    NSString *url = [NSString stringWithFormat:@"http://chat.scyd666.net/api/SendFile?fileName=%@&type=%d", fileName, type];
    OPHRequest* request = [OPHRequest jsonReqeust:url type:OPH_HTTP_GET];
    OPHResponse* response = [[OPHNetwork sharedInstance] syncRequest:request];
    if ([response isRequestOk] && [[[NSString alloc] initWithData:response.data encoding:NSUTF8StringEncoding]  isEqual: @"false"]) {
        int time = [[NSDate date] timeIntervalSinceNow];
        int nonce = (arc4random() % 10000000) + 1;//1-10000000
        NSString *signature = [NSString stringWithFormat:@"%d%dfse9aZbwzjysbmHKN1zULHQ", time, nonce];
        
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:[WCTConfig sharedInstance].batchCount];
        [dic setObject:[data base64EncodedStringWithOptions:0] forKey:@"value"];
        [dic setObject:@(nonce) forKey:@"nonce"];
        [dic setObject:@(time) forKey:@"timestamp"];
        [dic setObject:[[WCTConfig sharedInstance] sha1:signature] forKey:@"signature"];
        [dic setObject:fileName forKey:@"fileName"];
        [dic setObject:@(type) forKey:@"Type"];
        
        OPHRequest* sendRequest = [OPHRequest jsonReqeust:@"http://chat.scyd666.net/api/SendFile" type:OPH_HTTP_POST params:dic];
        OPHResponse* sendResponse = [[OPHNetwork sharedInstance] syncRequest:sendRequest];
        if ([sendResponse isRequestOk]) {
            NSLog(@"上传文件成功！FileName：%@", fileName);
            
            [self cacheImgForKey:fileName];
        }
    }
    else {
        NSLog(@"服务器已存在文件！FileName：%@", fileName);
        
        [self cacheImgForKey:fileName];
    }
}

-(void)cacheImgForKey:(NSString *)imgKey{
    //Key相同覆盖原本的Value
    [WCTConfig.sharedInstance.cacheImg addObject:imgKey];
    
//    //新增10条记录写入一次
//    if (WCTConfig.sharedInstance.cacheImg.count >= self.uploadedImgCount + 10) {
//        //写入plist
//        NSString *filePath = [self.filePath stringByAppendingPathComponent:str_wct_img];
//        [WCTConfig.sharedInstance.cacheImg writeToFile:filePath atomically:YES];
//        self.uploadedImgCount = WCTConfig.sharedInstance.cacheImg.count;
//    }
}

- (NSString *)getValueForXML:(NSString *)xml WithKey:(NSString *)key {
    NSString *temp = @"";
    NSRange range = [xml rangeOfString:[key stringByAppendingString:@"=\""]];
    if (range.length != 0) {
        temp = [xml substringFromIndex:range.location + range.length];
        NSArray<NSString *> *arr = [temp componentsSeparatedByString:@"\""];
        
        if (arr.count >= 1) {
            temp = arr[0];
        }
    }
    
    return temp;
}

-(NSString *)getCDATAForXML:(NSString *)xml WithKey:(NSString *)key {
    NSRange start = [xml rangeOfString:[NSString stringWithFormat:@"<%@>", key]];
    NSRange end = [xml rangeOfString:[NSString stringWithFormat:@"</%@>", key]];
    NSString *value = @"";
    if (start.length > 0 && end.length > 0 && end.location > start.location) {
        value = [xml substringWithRange: NSMakeRange(start.location + start.length, end.location - (start.location + start.length))];
        ///<![CDATA[¥0.02]]>
        value = [value stringByReplacingOccurrencesOfString:@"<" withString:@""];
        value = [value stringByReplacingOccurrencesOfString:@">" withString:@""];
        value = [value stringByReplacingOccurrencesOfString:@"!" withString:@""];
        value = [value stringByReplacingOccurrencesOfString:@"CDATA" withString:@""];
        value = [value stringByReplacingOccurrencesOfString:@"[" withString:@""];
        value = [value stringByReplacingOccurrencesOfString:@"]" withString:@""];
    }
    
    return value;
}

@end
